from pathlib import Path
import sys
from shutil import copytree, copyfile


class FileNotFound(Exception):
    pass


class FileCanNotCopyDirectory(Exception):
    pass


def _is_src_in_dest(src_path, dest_path):
    result = False
    for path in dest_path.iterdir():
        if path.name == src_path.name:
            result = True
            break

    return result


def _copy_file(src_path, dest_path):
    if not dest_path.is_dir():
        _cover_file(dest, src)
    else:
        dest_file_path = dest_path / src_path.name
        if _is_src_in_dest(src_path, dest_path):
            confirm = input("是否覆盖相同的目标文件(y/n): ")
            if confirm != 'y':
                sys.exit()

        _cover_file(src_path, dest_file_path)


def _cover_file(src_path, dest_path):
    with open(str(src_path), 'rb') as src_f:
        with open(str(dest_path), 'wb') as dest_f:
            dest_f.write(src_f.read())


def _copy_dir(src_path, dest_path):
    if not dest_path.is_dir():
        raise FileCanNotCopyDirectory

    if _is_src_in_dest(src_path, dest_path):
        confirm = input("是否覆盖相同的目标文件夹(y/n): ")
        if confirm != 'y':
            sys.exit()

    copytree(str(src_path), str(dest_path), dirs_exist_ok=True)


def copy(src_path, dest_path):
    src_path = Path(src_path)
    dest_path = Path(dest_path)

    if not src_path.exists():
        raise FileNotFound()

    if src_path.is_dir():
        _copy_dir(src_path, dest_path)
    else:
        _copy_file(src_path, dest_path)


if __name__ == '__main__':
    src = input("输入需要拷贝的源文件：")
    dest = input("输入拷贝到的文件目录：")
    copy(src, dest)

# 尝试实现下使用参数，类似于copy src_file dest_path